import 'babel-polyfill'
import Vue from 'vue'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import cui from '@cci/cui'
import { Message } from '@cci/cui'

import '@/styles/src/index.scss' // global css

import App from './App'

// import ErrorPage from './views/404.vue'
import router from './router/index'
import store from './store'
import axios from 'axios'
import { getToken, removeUserInfo, getWebsiteId } from '@/utils/auth'

import '@/icons' // icon
import '@/permission' // permission control

import '@/utils/codeData'
import '@/utils/codeConfigData'

import '@ztree/ztree_v3/js/jquery.ztree.core.min.js'
import '@ztree/ztree_v3/js/jquery.ztree.excheck.min.js'
// import '@ztree/ztree_v3/css/metroStyle/metroStyle.css'
import '@/styles/src/ztree.css'

Vue.use(cui)
// Vue.use(ElementUI, { locale })
Vue.config.productionTip = false

window.eventBus = new Vue()
const init = () => {
  new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App)
  })
}
const UrlAccesstokenLoginFlag = true
const urlPrefix =
  process.env.NODE_ENV === 'development'
    ? process.env.VUE_APP_API_URL_PREFIX
    : process.env.VUE_APP_API_URL_PREFIX

store.dispatch('GetSystemParmas')

if (UrlAccesstokenLoginFlag) {
  const token = getToken()
  const websiteId = getWebsiteId()
  // 如果地址栏有accestoken则校验是否有效
  // 获取用户相关信息
  axios
    .get(`${urlPrefix}v1/security/getCurrentUserInfo`, {
      headers: {
        token
      },
      params: {
        access_token: token,
        scope: websiteId
      }
    })
    .then(({ data }) => {
      if (data.success) {
        // 将用户相关信息存储到localStorage中
        data.data.token = token
        data.data.websiteId = websiteId
        store.dispatch('UrlAccesstokenLogin', data.data).then(() => {
          init()
        })
      } else {
        Message({
          type: 'error',
          message: data.message
        })
        setTimeout(() => {
          window.location.href = data.url
        }, 2000)
        // 如果accesstoken失效则删除localStorage用户相关信息，重新进行cas认证
        removeUserInfo()
        init()
      }
    })
} else {
  const token = getToken()
  const checkToken = () => {
    return new Promise((resolve, reject) => {
      axios
        .get(`${urlPrefix}v1/security/check`, {
          headers: {
            token: getToken()
          }
        })
        .then(({ data }) => {
          if (!data || !data.success) {
            reject()
          } else {
            resolve(data)
          }
        })
        .catch(() => {
          reject()
        })
    })
  }

  if (token) {
    checkToken()
      .then(() => {
        init()
      })
      .catch(() => {
        removeUserInfo()
        init()
      })
  } else {
    init()
  }
}
